package com.cskaoyan.service;

import com.cskaoyan.bean.bo.IssueCreateBo;
import com.cskaoyan.bean.entity.Issue;
import com.cskaoyan.bean.entity.IssueExample;
import com.cskaoyan.bean.vo.BasePageData;
import com.cskaoyan.bean.vo.BaseParam;
import com.cskaoyan.mapper.IssueMapper;
import com.cskaoyan.utils.MarketPageUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author break_a_leg
 * @description
 * @date 2021年10月19日 19:52
 */
@Service
public class IssueServiceImpl implements IssueService {

    @Autowired
    IssueMapper issueMapper;

    @Override
    public BasePageData list(String question, BaseParam param) {
        // 配置分页
        MarketPageUtil.startPage(param);

        IssueExample issueExample = new IssueExample();
        IssueExample.Criteria criteria = issueExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (!StringUtils.isEmpty(question)) {
            criteria.andQuestionLike("%" + question + "%");
        }

        // 设置排序
        issueExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<Issue> issues = issueMapper.selectByExample(issueExample);
        return BasePageData.ok(issues);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Issue create(IssueCreateBo issueCreateBo) {
        Issue issue = new Issue();
        issue.setQuestion(issueCreateBo.getQuestion());
        issue.setAnswer(issueCreateBo.getAnswer());
        issueMapper.insert(issue);
        Issue data = issueMapper.selectByUseGeneratedKeys(issue.getId());
        return data;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Issue update(Issue issue) {
        issueMapper.updateByPrimaryKey(issue);
        Issue data = issueMapper.selectByPrimaryKey(issue.getId());
        return data;
    }

    @Override
    public int delete(Issue issue) {
        int affectedRows = issueMapper.logicDeleteByPrimaryKey(issue.getId());
        return affectedRows;
    }

    @Override
    public BasePageData<Issue> getAllIssueList(BaseParam baseParam) {
        IssueExample issueExample = new IssueExample();
        // 设置分页
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());
        // 查询所有的issueList
        List<Issue> issueList = issueMapper.selectByExample(issueExample);
        return BasePageData.ok(issueList);
    }
}
